package ecweb.service.impl;

import java.util.List;

import ecweb.dal.DatabaseSession;
import ecweb.dao.IGoodDao;
import ecweb.dao.impl.GoodDao;
import ecweb.domain.GoodItem;
import ecweb.domain.GoodState;
import ecweb.exception.DatabaseException;
import ecweb.service.IGoodService;
import util.lang.RefValue;
import util.lang.sql.SqlOrderByType;

public class GoodService implements IGoodService {
	
	private IGoodDao goodDao=new GoodDao();

	@Override
	public GoodItem getGoodById(long id) throws DatabaseException {

		try (DatabaseSession dbses = new DatabaseSession()) {
			return goodDao.getGoodById(dbses, id);
		}

	}

	@Override
	public GoodItem addGood(String name, String description, double price,
			int inventory) throws DatabaseException {
		
		try (DatabaseSession dbses = new DatabaseSession(true)) {
			GoodItem good=new GoodItem();
			good.setName(name);
			good.setDescription(description);
			good.setPrice(price);
			good.setInventory(inventory);
			good.setState(GoodState.ON_SHELF);
			goodDao.addGood(dbses, good);
			
			if (!dbses.tryCommit()) {
				dbses.rollback();
			}
			
			return good;
		}
	}

	@Override
	public void deleteGood(long id) throws DatabaseException {
		
		try (DatabaseSession dbses = new DatabaseSession(true)) {
			GoodItem good=goodDao.getGoodById(dbses, id);
			good.setState(GoodState.OFF_SHELF);
			goodDao.updateGoodById(dbses, good);
			
			if (!dbses.tryCommit()) {
				dbses.rollback();
			}
			
		}

	}

	@Override
	public List<GoodItem> getGoods(String keyword, GoodState stateFilter,
			SqlOrderByType orderByPrice, SqlOrderByType orderByInventory,
			long limitStart, long limitLength, RefValue<Long> count)
			throws DatabaseException {
		
		try (DatabaseSession dbses = new DatabaseSession()) {
			
		if (count != null)
			count.setValue(goodDao.getGoodsCount(dbses, keyword, stateFilter));

		List<GoodItem> goodItem=goodDao.getGoods(dbses, keyword, stateFilter, orderByPrice, orderByInventory, limitStart, limitLength);
		return goodItem;
		}
	}

	@Override
	public long getGoodsCount(String keyword, GoodState stateFilter)
			throws DatabaseException {
		
		try (DatabaseSession dbses = new DatabaseSession()) {
			return goodDao.getGoodsCount(dbses, keyword, stateFilter);
		}
		
	}

}
